<?php
require_once "BaseAction.php";
class Event_HomeController extends TTEvent_Base_Action 
{
	
	public function init(){
		parent::init();
		$this->_helper->layout->setLayout('event');
	}
	
	
	
	public function indexAction() 
	{
	    $this->_helper->layout->setLayout('event-home');     
		     //   $this->_helper->layout->disableLayout();   
        $short_cut = $this->_getParam('short_cut', '');      
		if(ttCheckInput::checkShortCut($short_cut) && $this->checkNotKeyword($short_cut)){
			if($this->_helper->modelLoader->getEventInfoByShortcut($short_cut)
			&& file_exists(APPLICATION_PATH . '/modules/event/layouts/themes/'.$short_cut."/cover.phtml")
			){
				$this->_forward('cover');
			}
		}   
		
		$this->_helper->eventCommon->buildMainMenuBlock();
		$this->setTitle('Mạng xã hội chia sẻ video video, download video, video phim, movie trailers, kết bạn, làm quen');
		
		//-----------------
		$user = $this->getUser();
		$this->view->banners = $this->_helper->eventCommon->getBanner('home');
		
		//$cache_key = "event_home_data";
		$data = $this->getCache($cache_key);
		if(!$data){
			$eventModel = $this->loadModel('Event');
            $termModel = $this->loadModel('Term');
	//	cu~ @@
		//	$data['hotList'] = $eventModel->getHotList(0, 18);
		//	$data['lastestList'] = $eventModel->getLastestList();
    //        
    // va
            $data['focus']=$eventModel->getFocusEvent(1);
            $data['vipList']=$eventModel->getVipList(4);             
            $data['hotList']=$eventModel->getHotList2(4);
            $data['term']=$termModel->getTermOfType('event');       
        
       //va 
            
		//	$this->setCache($cache_key, $data);
		}
            $this->view->vipList = $data['vipList'];
            $this->view->hotList = $data['hotList'];
		    $this->view->focus = $data['focus'];
            $this->view->term=$data['term'];
            
		//$this->_helper->eventCommon->buildHtmlEventLeftMenu('home', $user->uid, 0, 0, false);
        $this->view->htmlSearchBox = $this->buildSearchBox($searchCond);
        //$testModel = $this->loadModel('test');   
        //$network['nw']=$testModel->getNetworkByType(1);       // dia diem
        //$this->view->list_nw = $this->view->partial('list_nw.phtml',$network);   
		
	}   

	
	public function cleancacheAction(){
        $this->_helper->layout->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);
	    $cacheKey = $this->_getParam('cachekey', '');
        if($cacheKey != ""){
            $this->deleteCache($cacheKey);
            echo "cache cleaned: ".$cacheKey;
        }
        else{
            echo "Not a cache key!";
        }
	}
	
	public function categoryAction(){
		$cid = $this->_getParam('cid', 0);
		if($cid == 10322)
			$cid = 10339;
		
		$this->_helper->getHelper('Redirector')->gotoUrlAndExit('http://video.tamtay.vn/category/'.$cid);
	}
	
	public function coverAction(){     
		
		$short_cut = $this->_getParam('short_cut', '');
		$layout = Zend_Layout::getMvcInstance();
		$layout->setLayoutPath( APPLICATION_PATH . '/modules/event/layouts/themes/'.$short_cut);
		
		$layout->spath = EVENT_STATIC_SERVER."/modules/event/themes/".$short_cut;
		$layout->short_cut = $short_cut;
		$this->_helper->layout->setLayout('cover');
		
		
		$view = $layout->getView();
		$view->setScriptPath(APPLICATION_PATH . '/modules/event/views/themes/'.$short_cut);
		
		$event = $this->_helper->modelLoader->getEventInfoByShortcut($short_cut);
		$vote_info = $this->_helper->modelLoader->eventVoteInfo($event->eid,0,0,0);
		
		$layout->vote_info = $vote_info;
        $layout->eid = $event->eid;
		
		$this->_helper->viewRenderer->setNoRender();
		$this->setTitle($event->event_name);
		
		//$is_admin = myttevent_is_admin($event->eid, $user->uid);
		$user = $this->getUser();
		$isAdmin = $this->_helper->modelLoader->isEventAdmin($event->eid, $user->uid);
		$thid = (int)$this->_getParam('thid', 0);
		$pid = (int)$this->_getParam('pid', 0);
        
        $content2 = $content = $this->_getParam('content', '');
        if($thid > 0 && $pid >0){
        	$content2 .= "_".$thid."_".$pid;
        }
        if($thid <= 0) $thid = 1;
        if($pid <= 0) $pid = 1;
        
		$cache_key = "html_event_home_page_".$event->eid."_".$content2.($isAdmin?"_1":"_0");
		
		$data = false;
		if(!isset($_GET['nocache']) || $_GET['nocache']!=1){
			$data = $this->getCache($cache_key);
		}
		
		if($data === false){
			$data = "";
			$assign_list = array();
			$assign_list["event"] = $event;
			$assign_list["spath"] = $layout->spath;
			$assign_list["top_block"] = $this->getEventTopBlock($event->eid, $vote_info);
			$assign_list["comment_block"] = $this->getEventCommentBlock($event->eid);
			
			switch ($content){
				case "votedlist":
					$layout->menu_active = 'vote_'.$thid.'_'.$pid;
					$phase = $vote_info[$thid][$pid];
					$eventResources = array();
					if($phase->vote_type == EVENT_PHOTO_VOTE)
						$eventResources = $this->eventPhotoVoteData($event->eid);
					else if($phase->vote_type == EVENT_MUSIC_VOTE)
						$eventResources = $this->eventMusicVoteData($event->eid);
					else if($phase->vote_type == EVENT_VIDEO_VOTE)
						$eventResources = $this->eventVideoVoteData($event->eid);
					$voteList = $eventResources[$thid][$pid];
					
					if(!empty($voteList)){
						$total_web_vote=0;
						$total_sms_vote=0;
						for ($i=0; $i<count($voteList); $i++)
						{
							$total_web_vote=$total_web_vote + $voteList[$i]->vote_web_count;
							$total_sms_vote=$total_sms_vote + $voteList[$i]->vote_sms_count;
						}
						
						$assign_list["voted_list"]=$voteList;
						$assign_list["vote_info"]= $phase;
						$assign_list["event"]=$event;
						
						$assign_list["total_vote_web"]=$total_web_vote;
						$assign_list["total_vote_sms"]=$total_sms_vote;
						if($phase->vote_type == EVENT_PHOTO_VOTE)
							$data = $this->view->partial("photo-voted-list.phtml", $assign_list);
						else if($phase->vote_type == EVENT_MUSIC_VOTE)
							$data = $this->view->partial("music-voted-list.phtml", $assign_list);
						else if($phase->vote_type == EVENT_VIDEO_VOTE)
							$data = $this->view->partial("video-voted-list.phtml", $assign_list);
					}
					
					break;
				case "desc":
                    $layout->menu_active = 'desc';
					$data = $this->view->partial("desc.phtml", $assign_list);
					break;
				default:
					$assign_list["isAdmin"] = $isAdmin;
					$layout->menu_active = 'home';
					// Main Block
					$assign_list["news_block"] = $this->getEventNewsBlock($event->eid);
					$assign_list["photo_block"] = $this->getEventPhotoBlock($event->eid, $vote_info);
					$assign_list["video_block"] = $this->getEventVideoBlock($event->eid, $vote_info);
					$assign_list["music_block"] = $this->getEventMusicBlock($event->eid, $vote_info);
					$assign_list["forum_block"] = $this->getEventForumBlock($event->eid);
					
					// Optional block
					$assign_list["slide_block"] = $this->getEventSlideBlock();
					
					$data = $this->view->partial("index.phtml", $assign_list);
			}
			
			$this->setCache($cache_key, $data);
			
		}
		
		$this->view->content = $data;
		$this->render('cover');    
	}
	
	
	public function getHomepageBannes(){
		$ret = array();
		$ret['center'][0] = $this->_helper->eventCommon->getBanner('home', 'center');
		$ret['bottom'][0] = $this->_helper->eventCommon->getBanner('home', 'bottom');
		$ret['right'][0] = $this->_helper->eventCommon->getBanner('home', 'left', 0);
		
		return $ret;
	}
	
	private function buildSearchBox($searchCond){
		$user = $this->getUser();
		//$networkList = $this->_helper->network->getUserNetworks($user->uid);
		//$networkList = $this->_helper->Network->getAllNetworks();
		$categoryList = $this->_helper->eventCommon->getEventCategories();
		
		return $this->_helper->eventCommon->buildHtmlSearchBox_Home($searchCond, $categoryList);
	}
	
	private function makeSearchCond(){
		$searchCond = array();
		
		$req = $this->getRequest();
		if($req->isPost()){
			$searchCond['keyword'] = $req->getPost('keyword', "");
			$searchCond['nwid'] = (int)$req->getPost('nwid', "");
			$searchCond['cid'] = (int)$req->getPost('cid', "");
			$searchCond['start_time'] = $req->getPost('start_time', "");
			$searchCond['end_time'] = $req->getPost('end_time', "");
		}
		else{
			$searchCond['keyword'] = $req->getQuery('keyword', "");
			$searchCond['nwid'] = $req->getQuery('nwid', 0);
			$searchCond['cid'] = $this->_getParam('cid', 0);
			$searchCond['start_time'] = $req->getQuery('start_time', "");
			$searchCond['end_time'] = $req->getQuery('end_time', "");
		}
		$searchCond['p'] = (int)$req->getPost('p', 0);
		if(!$searchCond['p']){
			$searchCond['p'] = (int)$req->getQuery('p', 0);
		}
		
		return $searchCond;
	}
	
	function checkNotKeyword($short_cut){
		$keyArr = array('home', 'blog', 'bookmark', 'browse', 'search', 'cat', 'city', 'comment', 
				'district', 'edit', 'cancel', 'detail', 'member', 'invite', 'attending', 'maybejoin', 
				'notjoin', 'join', 'request', 'leave', 'accept', 'makeadmin', 'removeadmin', 
				'removemember', 'music', 'my', 'photo', 'video');
		if(!in_array($short_cut, $keyArr))
			return true;
		return false;
	}
	
	
	public function getEventNewsBlock($eid){
		
		require_once 'lib/thrift/client/BlogService.php';
		$b_client = null;
		$eventBlogs = array();
		
		$eid = (int)$eid;

		try {
			$b_client = new BlogService(BLOG_THRIFT_SERVER, BLOG_THRIFT_PORT);
			$b_client->OpenTransport();
			$eventBlogs = $b_client->client()->getEventBlog($eid, 1, 5);
			$b_client->CloseTransport();
		} catch (Exception $ex){
			
		}
		
		return $this->view->partial('news-block.phtml', array('news'=>$eventBlogs));
	}
	
	public function getEventPhotoBlock($eid, $voteInfo){
		
		if(!$this->isPhotoVote($voteInfo))
			return "";
		
		$eid = (int)$eid;
		$event = $this->_helper->modelLoader->getEventInfo($eid);
		$eventPhotos = $this->eventPhotoVoteData($eid);
		$spath = EVENT_STATIC_SERVER."/modules/event/themes/".$event->short_cut;
		
		return $this->view->partial('photo-block.phtml', array('imgList'=>$eventPhotos, 'vote_info'=>$voteInfo, 'spath'=>$spath, 'event'=>$event));
	}
	public function getEventVideoBlock($eid, $voteInfo=null){
		if($this->isVideoVote($voteInfo)){
			$eid = (int)$eid;
			$event = $this->_helper->modelLoader->getEventInfo($eid);
			$eventVideos = $this->eventVideoVoteData($eid);
            $spath = EVENT_STATIC_SERVER."/modules/event/themes/".$event->short_cut;
			
			return $this->view->partial('video-block.phtml', array('videoList'=>$eventVideos, 'vote_info'=>$voteInfo, 'spath'=>$spath, 'event'=>$event));
		}
		else{
			require_once 'lib/thrift/client/VideoService.php';
			$v_client = null;
			$eventVideos = array();
			
			$eid = (int)$eid;

			try {
				$v_client = new VideoService(VIDEO_THRIFT_SERVER, VIDEO_THRIFT_PORT);
				$v_client->OpenTransport();
				$eventVideos = $v_client->client()->getEventVideo($eid, 1, 5);
				$v_client->CloseTransport();
			} catch (Exception $ex){
				
			}
			if(!is_array($eventVideos) || empty($eventVideos))
				return "";
			$video = (object) null;
			if(count($eventVideos) > 0){
				$keyrand = array_rand($eventVideos);
				$video = $eventVideos[$keyrand];
				if(count($eventVideos) > 4){
					//unset($eventVideos[$keyrand]);
				}
			}
			$eventVideos = array_values($eventVideos);
			
			return $this->view->partial('video-block.phtml', array('videos'=>$eventVideos, 'info'=>$video));
		}
	}
	public function getEventMusicBlock($eid, $voteInfo){
		
		if(!$this->isMusicVote($voteInfo))
			return "";
		
		$eid = (int)$eid;
		$event = $this->_helper->modelLoader->getEventInfo($eid);
		$eventMusics = $this->eventMusicVoteData($eid);
		
		return $this->view->partial('music-block.phtml', array('musicList'=>$eventMusics, 'vote_info'=>$voteInfo, 'event'=>$event));
	}

	public function getEventForumBlock($eid){
		return "";
		
	}
	public function getEventSlideBlock(){
		//return $this->view->partial('slide-block.phtml');
		return "";
	}
	public function getEventTopBlock($eid, $voteInfo){
		//$assign_list = event_ordered_list($short_cut, $limit);
		
		$event = $this->_helper->modelLoader->getEventInfo($eid);
		$topPhotoBlock = "";
		if($this->isPhotoVote($voteInfo)){
			$assign_list = array();
			$assign_list['spath'] = EVENT_STATIC_SERVER."/modules/event/themes/".$event->short_cut;
			$assign_list['short_cut'] = $event->short_cut;
			$assign_list['vote_info'] = $voteInfo;
			$assign_list['photoList'] = $this->eventPhotoVoteData($eid);
			$topPhotoBlock = $this->view->partial("photo-top-block.phtml", $assign_list);
		}
		
		$topMusicBlock = "";
		if($this->isMusicVote($voteInfo)){
			$assign_list = array();
			$assign_list['short_cut'] = $event->short_cut;
			$assign_list['vote_info'] = $voteInfo;
			$assign_list['musicList'] = $this->eventMusicVoteData($eid);
			$topMusicBlock = $this->view->partial("music-top-block.phtml", $assign_list);
		}
		
		$topVideoBlock = "";
		if($this->isVideoVote($voteInfo)){
			$assign_list = array();
			$assign_list['short_cut'] = $event->short_cut;
			$assign_list['vote_info'] = $voteInfo;
			$assign_list['videoList'] = $this->eventVideoVoteData($eid);
			$topVideoBlock = $this->view->partial("video-top-block.phtml", $assign_list);
		}
		$data = $topPhotoBlock."
		".$topMusicBlock."
		".$topVideoBlock;
		
		return $data;
	}
	public function getEventCommentBlock($eid){
		$user = $this->getUser();
		$event=  $this->_helper->modelLoader->getEventInfo($eid);
		return $this->view->partial('comment-block.phtml', array('user'=>$user, 'event'=>$event));
	}
	
	private function isPhotoVote($voteInfo){
		return $this->isVoted(EVENT_PHOTO_VOTE, $voteInfo);
	}
	
	private function isMusicVote($voteInfo){
		return $this->isVoted(EVENT_MUSIC_VOTE, $voteInfo);
	}
	
	private function isVideoVote($voteInfo){
		return $this->isVoted(EVENT_VIDEO_VOTE, $voteInfo);
	}
	
	private function isVoted($type, $voteInfo){
		if(!is_array($voteInfo) || count($voteInfo) <=0)
			return false;
		else{
			$idx = 0;
			foreach($voteInfo as $thread){
				if(is_array($thread) && count($thread) >0){
					foreach ($thread as $phase){
						if($phase->vote_type == $type && ($phase->vote_enable==1 || $phase->view_enable==1)){
							$idx++;
							break;
						}
					}
				}
				if($idx>0)
					break;
			}
			if($idx==0)
				return false;
		}
		
		return true;
	}
	
	public function mergeResourceObject($eid, $type, $itemList){
		
		$smsModel = $this->loadModel('Sms');
		$resourceList = $smsModel->getEventSms($eid, 0, 0, $type);
        $changeArr = array('vote_count'=>'vote_web_count');
		
		switch ($type){
			case EVENT_PHOTO_VOTE:
				$itemIdKey = 'aid';
				break;
			case EVENT_MUSIC_VOTE:
				$itemIdKey = 'sid';
                $changeArr = array('like_count'=>'vote_web_count');
				break;
			case EVENT_VIDEO_VOTE:
				$itemIdKey = 'vid';
                $changeArr = array('like_count'=>'vote_web_count');
				break;
		}
		
		$eventResources = array();
		
		for($i=0; $i<count($resourceList); $i++){
			$obj = $resourceList[$i];
			
			$obj = searchAndMergeObject($obj, $itemList, array('rid'=>$itemIdKey), $changeArr);
			
			if($obj){
				$imgArr[] = $obj;
				if($obj->thid > 0 && $obj->pid >0){
					$eventResources[$obj->thid][$obj->pid][] = $obj;
				}
				else{
					// List albums of event that is not voted
					$eventResources["nomal"][] = $obj;
				}
			}
		}

		return $eventResources;
	}
	
	
	public function eventPhotoVoteData($eid){
	
		$resourceList = array();
		
		require_once 'lib/thrift/client/PhotoService.php';
		$p_client = null;
		$event_photo_list = array();
		$event = $this->_helper->modelLoader->getEventInfo($eid);
		
		try {
			$p_client = new PhotoService(PHOTO_THRIFT_SERVER, PHOTO_THRIFT_PORT);
			$p_client->OpenTransport();
			$totalPhoto = $p_client->client()->getEventAlbumCount($eid);
			if($totalPhoto > 0)
			$event_photo_list = $p_client->client()->getEventAlbum($eid, 1, $totalPhoto);
			$p_client->CloseTransport();
		} catch (Exception $ex){
			//var_dump($ex);exit();
		}
		
		if(!is_array($event_photo_list) || empty($event_photo_list))
			return array();
        
        return $this->mergeResourceObject($eid, EVENT_PHOTO_VOTE, $event_photo_list);
	}
	
	public function eventMusicVoteData($eid){
	
		$resourceList = array();
		
		require_once 'lib/thrift/client/MusicService.php';
		$p_client = null;
		$event_music_list = array();
		$event = $this->_helper->modelLoader->getEventInfo($eid);
		
		try {
			$p_client = new MusicService(MUSIC_THRIFT_SERVER, MUSIC_THRIFT_PORT);
			$p_client->OpenTransport();
			$totalMusic = $p_client->client()->getEventMusicCount($eid);
			if($totalMusic > 0)
			$event_music_list = $p_client->client()->getEventMusic($eid, 1, $totalMusic);
			$p_client->CloseTransport();
		} catch (Exception $ex){
			//var_dump($ex);exit();
		}
		if(!is_array($event_music_list) || empty($event_music_list))
			return array();
		$user = $this->getUser();
        
		return $this->mergeResourceObject($eid, EVENT_MUSIC_VOTE, $event_music_list);
	}
	
	
	public function eventVideoVoteData($eid){
	
		$resourceList = array();
		
		require_once 'lib/thrift/client/VideoService.php';
		$p_client = null;
		$event_video_list = array();
		$event = $this->_helper->modelLoader->getEventInfo($eid);
		
		try {
			$p_client = new VideoService(VIDEO_THRIFT_SERVER, VIDEO_THRIFT_PORT);
			$p_client->OpenTransport();
			$totalVideo = $p_client->client()->getEventVideoCount($eid);
			if($totalVideo > 0)
			$event_video_list = $p_client->client()->getEventVideo($eid, 1, $totalVideo);
			$p_client->CloseTransport();
		} catch (Exception $ex){
			//var_dump($ex);exit();
		}
		if(!is_array($event_video_list) || empty($event_video_list))
			return array();
		$user = $this->getUser();
        
		return $this->mergeResourceObject($eid, EVENT_VIDEO_VOTE, $event_video_list);
	}
}

